<template>
  <div class="details">
    <van-nav-bar
      title="商品详情"
      left-text="返回"
      left-arrow
      @click-left="back"
    />
    <div class="largeImg">
      <img :src="detailData.large_img" />
    </div>
    <div class="detailInfo">
      <div class="goodsMsg">
        <div class="goodsName">
          <p>{{ detailData.name }}</p>
          <p>{{ detailData.enname }}</p>
        </div>
        <div class="goodsPrice">&yen;{{ detailData.price }}</div>
      </div>
      <div class="goodsSpecs">
        <div class="specs" v-for="(v1, i1) in detailData.rulesData" :key="i1">
          <p class="specsTitle">{{ v1.title }}</p>
          <div class="specsSelect">
            <div
              :class="{ active: v1.currentIndex === i2 }"
              @click="changeSpecs(v1, i2)"
              v-for="(v2, i2) in v1.rule"
              :key="i2"
            >
              {{ v2.title }}
            </div>
          </div>
        </div>
      </div>
      <div class="selectCount">
        <span>选择数量</span>
        <div class="count">
          <van-stepper
            v-model="count"
            theme="round"
            button-size="22"
            disable-input
          />
        </div>
      </div>
      <div class="description">
        <h3>商品描述</h3>
        <p v-for="(de, k) in detailData.desc" :key="k" class="desc">
          {{ k + 1 }}、{{ de }}
        </p>
      </div>
      <div class="buy">
        <van-goods-action>
          <van-goods-action-icon
            icon="cart-o"
            text="购物车"
            color="#CC9145"
            :badge="shopCount > 0 ? shopCount : ''"
            @click="goShopCar"
          />
          <van-goods-action-icon
            icon="like"
            :text="like ? '已收藏' : '收藏'"
            :color="like ? '#CC9145' : '#666'"
            @click="collection"
          />
          <van-goods-action-button
            type="warning"
            text="加入购物车"
            @click="addShopCar"
          />
          <van-goods-action-button
            color="#CC9145"
            type="danger"
            text="立即购买"
          />
        </van-goods-action>
      </div>
    </div>
  </div>
  <!-- #F6F0F3备用底色 -->
</template>

<script>
import "../assets/less/details.less";
import { mapState, mapMutations } from "vuex";
export default {
  name: "Details",
  data() {
    return {
      pid: "",
      detailData: {},
      like: false,
      count: 1,
    };
  },
  methods: {
    ...mapMutations(["changeShopCount", "changeLoadShopCount"]),

    getGoodsDetail() {
      this.$axios({
        method: "GET",
        url: "/productDetail",
        params: {
          appkey: this.appkey,
          pid: this.pid,
        },
      })
        .then((res) => {
          // console.log("res getGoodsDetails ==> ", res);
          this.$toast.clear();

          if (res.data.code === 600) {
            let data = res.data.result[0];
            let rules = ["cream", "milk", "sugar", "tem"];
            data.rulesData = [];

            rules.forEach((v) => {
              if (!data[v]) {
                return;
              }

              let rulesText = data[v].split("/");

              let currentRule = {
                title: data[v + "_desc"],
                currentIndex: 0,
                rule: [],
              };

              rulesText.forEach((item) => {
                let o = {
                  title: item,
                };
                currentRule.rule.push(o);
              });

              data.rulesData.push(currentRule);
            });

            data.desc = data.desc.split(/\n/);

            // console.log("data ==> ", data);

            this.detailData = data;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    back() {
      this.$router.go(-1);
    },
    changeSpecs(v, i) {
      if (v.currentIndex === i) {
        return;
      } else {
        v.currentIndex = i;
      }
    },
    collection() {
      if (this.like) {
        this.noCollect();
      } else {
        this.collect();
      }
    },
    collect() {
      let tokenString = this.$cookies.get("tokenString");
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.$axios({
        method: "POST",
        url: "/like",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          // console.log("res collect ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 800) {
            this.like = true;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    noCollect() {
      let tokenString = this.$cookies.get("tokenString");
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.$axios({
        method: "POST",
        url: "/notlike",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          // console.log("res noCollect ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 900) {
            if (res.data.result === 1) {
              this.like = false;
            }
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 3000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    getCollection() {
      let tokenString = this.$cookies.get("tokenString");
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.$axios({
        method: "GET",
        url: "/findlike",
        params: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
        },
      })
        .then((res) => {
          // console.log("res getLikeProduct ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            return;
          }

          if (res.data.code === 1000 && res.data.result.length > 0) {
            this.like = true;
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    addShopCar() {
      let tokenString = this.$cookies.get("tokenString");
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }

      let rules = [];
      this.detailData.rulesData.forEach((v) => {
        rules.push(v.rule[v.currentIndex].title);
      });
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      this.$axios({
        method: "POST",
        url: "/addShopcart",
        data: {
          appkey: this.appkey,
          pid: this.pid,
          tokenString,
          count: this.count,
          rule: rules.join("/"),
        },
      })
        .then((res) => {
          // console.log("res addShopCar ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 3000) {
            if (res.data.status === 1) {
              this.changeShopCount(this.shopCount + 1);

              this.$toast({
                message: res.data.msg,
                forbidClick: true,
                duration: 1000,
              });
            }
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    getShopCount() {
      if (this.loadShopCount) {
        // console.log('Detail 已经加载过购物袋数量, 不再请求');
        return;
      }
      let tokenString = this.$cookies.get("tokenString");
      if (!tokenString) {
        return;
      }
      this.$toast.loading({
        message: "加载中",
        forbidClick: true,
        duration: 0,
      });

      this.$axios({
        method: "GET",
        url: "/shopcartRows",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((res) => {
          // console.log("res getShopcartCount ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            return;
          }

          if (res.data.code === 8000) {
            this.changeShopCount(res.data.result);

            this.changeLoadShopCount(true);
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    goShopCar() {
      this.$router.push({ name: "ShopCar" });
    },
  },
  computed: {
    ...mapState(["shopCount", "loadShopCount"]),
  },
  created() {
    this.pid = this.$route.params.pid;
    this.getGoodsDetail();
    this.getCollection();
    this.getShopCount();
  },
};
</script>

<style lang="less" scoped>
</style>